<?php

declare(strict_types=1);

namespace app\api\model;

use app\api\service\UserToken;
use app\api\model\Native as ModelNative;
use app\api\model\Course as ModelCourse;
use think\model\concern\SoftDelete;
use app\api\model\Source as ModelSource;
use think\facade\Request;
use app\api\model\Province as ModleProvince;
use app\api\model\City as ModelCity;
use app\api\model\Semester as ModelSemester;

/**
 * 前台会员模型
 */
class Student extends Base
{
    use SoftDelete;
    protected $autoWriteTimestamp = 'datetime';
    protected $deleteTime = 'delete_time';


    /**
     * 获取单条记录
     */
    public static function get($id)
    {
        return self::where('status', self::STATUS_NORMAL)->find($id);
    }

    /**
     * 密码自动加密处理
     */
    public static function onBeforeInsert($user)
    {
        $password = isset($user->password) ? $user->password : 'www.52document.com';
        $user->password = password_hash(md5($password), PASSWORD_DEFAULT);
    }

    /**
     * 验证登录
     * @param 会员账户
     * @param 会员密码
     */
    public function checkLogin($account = '', $password = '')
    {
        $account  = trim($account);
        $password = trim($password);

        $map = [];
        $map[] = ['status', '=', 1];
        $map[] = ['account', '=', $account];

        $user = self::where($map)->field('id,account,password,avatar,amount')->find();
        if (empty($user)) {
            $this->error = '用户不存在或被禁用！';
            return false;
        }

        $arrUser = $user->toArray();
        // 密码校验
        if (!password_verify($password, $arrUser['password'])) {
            $this->error = '登陆密码错误！';
            return false;
        }
        unset($arrUser['password']);
        return $arrUser;
    }

    /**
     * @param string $truename
     * @param string $native
     * @return array|false|null
     * @throws \think\db\exception\DbException
     * 学生查询
     */
    public function lookup($truename = '', $native = '')
    {
        //获取登录的老师id
        $uid =  UserToken::getCurrentUid();
        $where = [
            ['truename', 'like', '%' . $truename . '%'],
            ['native_id', 'like', '%' . $native . '%']
        ];
        $truename = self::where($where)->find();
        if ($truename == null) {
            $this->error = '学生不存在或被禁用！';
            return false;
        }

        $lookup = self::where($where)->alias('l')
            ->join('native n', 'l.native_id = n.id')
            ->where('teacher_id', $uid)
            ->join('Tea_stu_rel t', "t.student_id = l.id") //中间表的学生id 查 学生表id
            ->field("l.id,l.truename,l.course,l.account,l.progress,l.birthday,n.province")
            ->order('l.create_time', 'desc')->limit(10)->select();

        //计算年龄
        foreach ($lookup as $key => $value) {
            $lookup[$key]['age'] = self::getBirthday($lookup[$key]['birthday']);
        }

        return $lookup ? $lookup->toArray() : null;
    }

    /**
     *  # 获取当前课程学生
     * @param string $course_id
     * @return object
     */
    public static function getStudent($course_ids, $option = 'select')
    {
        $field = 'id,truename,course_id,account,progress,gender,birthday,referrer,source_id,city_code,province_code,semester_id,apply_time';
        $where = [];
        if (is_string($course_ids) || is_int($course_ids)) {
            $where[] = ['course_id', '=', $course_ids];
        } else if (is_array($course_ids)) {
            $where[] = ['course_id', 'in', $course_ids];
        } else {
            return false;
        }
        $student = Student::where($where)->field($field)->$option();
        return $student;
    }
    /**
     * 切换信息名字
     */

    public static function onAfterRead($user)
    {
        //方法为删除不转换
        if ('delete' == Request::action()) {
            return;
        }
        //性别
        if (isset($user->gender)) {
            $arr = ['女', '男'];
            $user->gender_name = $arr[$user->gender];
        }
        //课程
        if (isset($user->course_id)) {
            $user->course_name = ModelCourse::find($user->course_id)['name'];
        }
        //计算年龄
        if (isset($user->birthday)) {
            $birthday = $user->birthday;
            $date = date("Y-m-d");
            list($year, $month, $today) = explode("-", $birthday);
            list($toyear, $thisMonth, $today) = explode("-", $date);
            $age = $toyear - $year;
            if ($thisMonth > $month || $thisMonth == $month && $today > $today) {
                $age = $age + 1;
            }
            $user->age =  $age;
        }
        //来源
        if (isset($user->source_id)) {
            $user->source_name = ModelSource::find($user->source_id)->title;
        }
        //省
        if (isset($user->province_code)) {
            $user->province_name = ModleProvince::where('province_code', $user->province_code)->find()['name'];
        }
        //市
        if (isset($user->city_code)) {
            $user->city_name = ModelCity::where('city_code', $user->city_code)->find()['name'];
        }
        //学期
        if (isset($user->semester_id)) {
            $user->semester_name = ModelSemester::find($user->semester_id)['name'];
        }
    }
}
